<template>
  <div>
    <el-date-picker
      v-model="selectValue"
      :disabled="disabled"
      :end-placeholder="endPlaceholder"
      :format="dateFormat"
      :placeholder="placeholder"
      :readonly="readonly"
      :start-placeholder="startPlaceholder"
      :type="type"
      :value-format="dateValueFormate"
      @change="onHandleChange"
    />
  </div>
</template>

<script>
  export default defineComponent({
    name: 'CommonDatePicker',
    props: {
      modelValue: {
        type: String,
        default: '',
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      readonly: {
        type: Boolean,
        default: false,
      },
      placeholder: {
        type: String,
        default: '',
      },
      startPlaceholder: {
        type: String,
        default: '',
      },
      endPlaceholder: {
        type: String,
        default: '',
      },
      dateFormat: {
        type: String,
        default: 'YYYY-MM-DD',
      },
      dateValueFormate: {
        type: String,
        default: 'YYYY-MM-DD',
      },
      subName: {
        type: String,
        default: '',
      },

      type: {
        type: String,
        default: 'date',
      },
    },

    emits: {
      'update:model-value': null,
      'update:sub-name': null,
      change: null,
    },

    setup(props, { emit }) {
      const selectValue = ref('')

      const isRange = computed(() => {
        const index = props.type.indexOf('range')
        return index >= 0
      })

      const onHandleChange = (value = []) => {
        if (isRange.value) {
          const newVal = value || []
          emit('update:model-value', newVal[0])
          emit('update:sub-name', newVal[1])
          emit('change', newVal)
        } else {
          emit('update:model-value', value)
          emit('change', value)
        }
      }

      watch(
        [() => props.modelValue, () => props.subName],
        (newVal) => {
          const index = props.type.indexOf('range')
          if (~index) {
            if (!selectValue.value) {
              selectValue.value = newVal
            } else if (selectValue.value.toString() !== newVal.toString()) {
              //判断数组值是否相同
              selectValue.value = newVal
            }
          } else {
            if (newVal != selectValue.value) {
              selectValue.value = props.modelValue
            }
          }
        },
        {
          immediate: true,
        }
      )

      // watch(
      //   () => isRange.value,
      //   (newVal) => {
      //     if (newVal) {
      //       selectValue.value = [props.modelValue, props.subName]
      //     }
      //   },
      //   {
      //     immediate: true,
      //   }
      // )

      return {
        selectValue,
        onHandleChange,
      }
    },
  })
</script>

<style lang="scss" scoped></style>
